Components.utils.import("resource://lucidity/lucidapi.jsm");
Components.utils.import("resource://gre/modules/JSON.jsm");

var myObserver =
{
    startup: function()
    {
        var observerService = lucidapi.getXpcomService("@mozilla.org/observer-service;1", "nsIObserverService");
        observerService.addObserver(this,"lucid-logmsg",false);
        this.prefs = lucidapi.config.getLucidPrefBranch();
        this.prefs.QueryInterface(Components.interfaces.nsIPrefBranch2);
        this.prefs.addObserver("", this, false);
        this.refreshInformation();
    },

    observe: function( subject, topic, data )
    {
        switch (topic) {
            case "lucid-logmsg":
                addStuffToLog(data);
                break;
            case "nsPref:changed":
                switch (data) {
                    case "keystore_path":
                    case "hide_expired":
                    case "enable_keysync":
                        this.refreshInformation();
                        break;
                }
                break;
        }

    },

    shutdown: function()
    {
        var observerService = lucidapi.getXpcomService("@mozilla.org/observer-service;1", "nsIObserverService");
        observerService.removeObserver(this,"lucid-logmsg");
        this.prefs.removeObserver("", this);
    },

    refreshInformation: function()
    {
        var keypathtxtbox = document.getElementById("keystore-path-textbox");
        keypathtxtbox.value = lucidapi.config.keystore_path;
        updateKeyMenulist(document.getElementById("defkey-menulist"));
        updateGenericBox(document.getElementById('pubkeylist'),false);
        updateGenericBox(document.getElementById('seckeylist'),true);
    }
}


function chooseKeystorePath(reset)
{
    var keyringFolder = null;
    if (reset)
    {
        keyringFolder = "";
    }
    else
    {
        keyringFolder = lucidapi.openFileSelector(window, true, document.getElementById("keystore-path-textbox").value);
    }

    if (keyringFolder != null)
    {
        var preference = document.getElementById("keystore-path-pref");
        preference.value = keyringFolder;
    }
}

function doKeygen()
{
    lucidapi.openKeygenWizard();
    myObserver.refreshInformation();
}

function onKeytreeContextCommand(event)
{
    var cmd = event.target.id;
    var parnode = event.target.parentNode;
    var keytype = parnode.getAttribute("keytype");
    var keyid = parnode.getAttribute("keyid");
    switch (cmd) {
        case "keytreemenu-export":
            lucidapi.exportKeys(window,(keytype.indexOf("sec") == 0),keyid);
            break;
        case "keytreemenu-delete":
            lucidapi.masterKeyset.removeKey((keytype.indexOf("sec") == 0),keyid);
            myObserver.refreshInformation();
            break;
    }
}

function handleKeytreeClick(event){
    if (event.button < 2)
        return;
    var row = {}, column = {}, part = {};
    var tree = event.currentTarget;
    var treemenu = document.getElementById('keytreemenu');

    var boxobject = tree.boxObject;
    boxobject.QueryInterface(Components.interfaces.nsITreeBoxObject);
    boxobject.getCellAt(event.clientX, event.clientY, row, column, part);

    var treecolel = document.getElementById(tree.parentNode.id + "-" + "keyid");
//    lucidapi.error("treecolel: %s", Boolean(treecolel));
    var primecol = tree.columns.getColumnFor(treecolel);
    if (row.value > -1)
    {
        var label = tree.view.getCellText(row.value,primecol);
//        lucidapi.error("keyid: %s", label);
        treemenu.setAttribute("keytype",tree.parentNode.id);
        treemenu.setAttribute("keyid",label);
        treemenu.openPopup(null,"overlap",event.clientX,event.clientY,true,false);
    }
}

function clearLogMessages()
{
    lucidapi.logmsgs.length = 0;
    var treechildren = document.getElementById('lucid-logtreechildren');
    if (!treechildren)
        return;
    while (treechildren.firstChild)
        treechildren.removeChild(treechildren.firstChild);
}

function addLogSourceRow(treechildren,label)
{
    var logdoc = treechildren.ownerDocument;
    var treeitem2 = logdoc.createElement("treeitem");
    treechildren.appendChild(treeitem2);
    var treerow2 = logdoc.createElement("treerow");
    treeitem2.appendChild(treerow2);
    var treecell2 = logdoc.createElement("treecell");
    treerow2.appendChild(treecell2);
    treecell2.setAttribute("label",label);
    return treeitem2;
}

function calcDateString(dateObj,extended)
{
    if (typeof(dateObj) == "number")
    {
        var timestamp = dateObj;
        dateObj = new Date();
        dateObj.setTime(timestamp);
    }
    var retval = lucidapi.sprintf("%04d-%02d-%02d",dateObj.getFullYear(),dateObj.getMonth() + 1,dateObj.getDate());
    if (extended)
    {
        retval += lucidapi.sprintf(" %02d:%02d:%02d.%03d",dateObj.getHours(),dateObj.getMinutes(),dateObj.getSeconds(),dateObj.getMilliseconds())
    }

    return retval;
};

function addStuffToLog(logmsg)
{
    var treechildren = document.getElementById('lucid-logtreechildren');
    if (!treechildren)
        return;
    logmsg = JSON.fromString(logmsg);
    var tstamp = logmsg.tstamp;
    var msg = logmsg.message;
    var stack = logmsg.stack;
    var logdoc = treechildren.ownerDocument;
    var treeitem = addLogSourceRow(treechildren,"" + calcDateString(tstamp,true) + " " + msg);

    var treechildren2 = logdoc.createElement("treechildren");
    treeitem.appendChild(treechildren2);
    treeitem.setAttribute("container","true");

    while (stack)
    {
        addLogSourceRow(treechildren2,stack.filename + ":" + stack.lineNumber);
        stack = stack.caller;
    }
}

function handleLogtreeClick(event){
  var row = {}, column = {}, part = {};
  var tree = event.currentTarget;

  var boxobject = tree.boxObject;
  boxobject.QueryInterface(Components.interfaces.nsITreeBoxObject);
  boxobject.getCellAt(event.clientX, event.clientY, row, column, part);

    if (row.value > -1)
    {
        var level = tree.view.getLevel(row.value,column.value);
        if (level > 0)
        {
            var label = tree.view.getCellText(row.value,column.value);
            var colIdx = label.lastIndexOf(":");
            var lineno = parseInt(label.substr(colIdx + 1),10);
            var fileurl = label.substr(0,colIdx);
            lucidapi.openViewSource(fileurl,lineno);
        }
    }
}

function onLoad( /* win */ )
{
    var tree = document.getElementById("lucid-logtree");
    if (tree)
    {
        tree.addEventListener("click", handleLogtreeClick, false);
        for (var ii = 0; ii < lucidapi.logmsgs.length; ii++)
        {
            addStuffToLog(lucidapi.logmsgs[ii]);
        }
    }
    myObserver.startup();
//    apiObserver.register();
    document.getElementById('pubkeylist').getTree().addEventListener("click", handleKeytreeClick, false);
    document.getElementById('seckeylist').getTree().addEventListener("click", handleKeytreeClick, false);
    if ("selfTest" in lucidapi)
    {
        document.getElementById("selftest-button").hidden = false;
    }
}

function onUnload( /* win */ )
{
    myObserver.shutdown();
//    apiObserver.unregister();
}
